/**
 * Copyright &copy; 2017-2020 <a href="http://www.fosung.com/">FosungFrame</a> All rights reserved.
 */
package com.fosung.frame.modules.approve.web;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.fosung.frame.common.config.Global;
import com.fosung.frame.common.persistence.Page;
import com.fosung.frame.common.utils.StringUtils;
import com.fosung.frame.common.web.BaseController;
import com.fosung.frame.modules.approve.entity.HomeApprove;
import com.fosung.frame.modules.approve.service.HomeApproveService;
import com.fosung.frame.modules.checkinfos.entity.Checkinfos;
import com.fosung.frame.modules.checkinfos.service.CheckinfosService;
import com.fosung.frame.modules.life.entity.OrganizeLifeType;
import com.fosung.frame.modules.life.service.OrganizeLifeTypeService;
import com.fosung.frame.modules.sys.utils.UserUtils;

/**
 * 组织生活计划管理Controller
 * @author ygl
 * @version 2017-08-30
 */
@Controller
@RequestMapping(value = "${adminPath}/approve/planApprove")
public class PlanApproveController extends BaseController {

	@Autowired
	private HomeApproveService homeApproveService;
	
	@Resource
	private OrganizeLifeTypeService organizeLifeTypeService;
	
	@Autowired
	private CheckinfosService checkinfosService;
	
	@ModelAttribute
	public HomeApprove get(@RequestParam(required=false) String id) {
		HomeApprove entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = homeApproveService.get(id);
		}
		if (entity == null){
			entity = new HomeApprove();
		}
		return entity;
	}
	
	@RequiresPermissions("approve:planApprove:view")
	@RequestMapping(value = {"list", ""})
	public String list(HomeApprove homeApprove, HttpServletRequest request, HttpServletResponse response, Model model) {
		homeApprove.setOrganizationid(UserUtils.getUser().getOffice().getId());
		Page<HomeApprove> page = homeApproveService.findPlanApprovePage(new Page<HomeApprove>(request, response), homeApprove); 
		model.addAttribute("page", page);
		model.addAttribute("starttime", homeApprove.getStarttime());
		model.addAttribute("endtime", homeApprove.getEndtime());
		return "modules/approve/planApproveList";
	}

	@RequiresPermissions("approve:planApprove:view")
	@RequestMapping(value = "form")
	public String form(HomeApprove homeApprove, Model model) throws ParseException {
		 //循环获取审批意见，然后赋值
		Checkinfos ci = new Checkinfos();
		ci.setOrganizeLifeId(homeApprove.getId());
		List<Checkinfos> listCheckinfos = checkinfosService.findList(ci);
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String userId = UserUtils.getUser().getId();
		String username = UserUtils.getUser().getName();
		model.addAttribute("username", username);
		
		if (listCheckinfos.size() > 0) {
			if(listCheckinfos.get(0).getApproveStatus().equals(homeApprove.getJhstate())) {
				ci = listCheckinfos.get(0);
				ci.setShTime(format.format(ci.getCreateDate()));
				homeApprove.setCheckinfos(ci);
			}
		}else {
			ci.setApproveUserId(userId);
			ci.setShTime(format.format(new Date()));
			homeApprove.setCheckinfos(ci);
		}
		
		
		List<OrganizeLifeType> listStr=new ArrayList<OrganizeLifeType>();
		if (homeApprove.getTypeids() != null && !homeApprove.getTypeids().equals("")) {
			String[] types = homeApprove.getTypeids().split(",");
			
			if (types != null && types.length > 0) {
				for (String s : types) {
					// 循环遍历数组中元素，添加到StringBuilder 对象中
					OrganizeLifeType o=new OrganizeLifeType();
					String t = organizeLifeTypeService.get(s).getTypename();
					o.setTypename(t);
					listStr.add(o);
				}
				model.addAttribute("listStr", listStr);
			}
		}
		model.addAttribute("homeApprove", homeApprove);
		
		Map<Integer, String> yyzlmap = new HashMap<Integer, String>();
		if (homeApprove.getYyzl() != null && !homeApprove.getYyzl().equals("")) {
			String[] yyzl = homeApprove.getYyzl().split("\\|");
			for (int i = 1; i < yyzl.length; i++) {
				yyzlmap.put(i, yyzl[i]);
			}
			model.addAttribute("yyzlmap", yyzlmap);
		}

		Map<String, String> fjmap = new HashMap<String, String>();
		if (homeApprove.getFujian() != null && !homeApprove.getFujian().equals("")) {
			String[] fj = homeApprove.getFujian().split("\\|");
			for (int i = 1; i < fj.length; i++) {
				File tempFile = new File(fj[i].trim());
				String fileName = tempFile.getName();
				try {
					fjmap.put(fj[i], URLDecoder.decode(fileName, "utf-8"));
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			}
			model.addAttribute("fjmap", fjmap);
		}
		return "modules/approve/planApproveForm";
	}
	
	@RequiresPermissions("approve:planApprove:edit")
	@RequestMapping(value = "updateApproveState")
	public String updateApproveState(HomeApprove planApprove, RedirectAttributes redirectAttributes) {
		String[] ids = planApprove.getIds().split(",");
		try {
			for(int i=0; i<ids.length; i++) {
				planApprove.setId(ids[i]);
				homeApproveService.updateApproveJhState(planApprove);
			}
			addMessage(redirectAttributes, "操作成功！");
		}catch(Exception e) {
			addMessage(redirectAttributes, "操作失败！");
		}
		return "redirect:"+Global.getAdminPath()+"/approve/planApprove/?repage";
	}
	
	
	@RequiresPermissions("approve:planApprove:edit")
	@RequestMapping(value = "save")
	public String save(HomeApprove homeApprove, Model model, RedirectAttributes redirectAttributes) throws ParseException {
		if (!beanValidator(model, homeApprove)){
			return form(homeApprove, model);
		}
		try {
			homeApproveService.updateShyj(homeApprove);
			addMessage(redirectAttributes, "审批成功！");
		}catch(Exception e) {
			addMessage(redirectAttributes, "审批失败！");
		}
		return "redirect:"+Global.getAdminPath()+"/approve/planApprove/?repage";
	}
	
	/**
	 * 跳转到修改页面
	 * @param homeApprove
	 * @param model
	 * @return
	 */
	@RequiresPermissions("approve:planApprove:view")
	@RequestMapping(value = "editHomeApprove")
	public String editHomeApprove(HomeApprove homeApprove, Model model){
		List<OrganizeLifeType> listStr=new ArrayList<OrganizeLifeType>();
		if (homeApprove.getTypeids() != null && !homeApprove.getTypeids().equals("")) {
			String[] types = homeApprove.getTypeids().split(",");
			if (types != null && types.length > 0) {
				for (String s : types) {
					// 循环遍历数组中元素，添加到StringBuilder 对象中
					OrganizeLifeType o=new OrganizeLifeType();
					String t = organizeLifeTypeService.get(s).getTypename();
					o.setTypename(t);
					listStr.add(o);
				}
				model.addAttribute("listStr", listStr);
			}
		}
		model.addAttribute("homeApprove", homeApprove);
		
		Map<Integer, String> yyzlmap = new HashMap<Integer, String>();
		if (homeApprove.getYyzl() != null && !homeApprove.getYyzl().equals("")) {
			String[] yyzl = homeApprove.getYyzl().split("\\|");
			for (int i = 1; i < yyzl.length; i++) {
				yyzlmap.put(i, yyzl[i]);
			}
			model.addAttribute("yyzlmap", yyzlmap);
		}

		Map<String, String> fjmap = new HashMap<String, String>();
		if (homeApprove.getFujian() != null && !homeApprove.getFujian().equals("")) {
			String[] fj = homeApprove.getFujian().split("\\|");
			for (int i = 1; i < fj.length; i++) {
				File tempFile = new File(fj[i].trim());
				String fileName = tempFile.getName();
				try {
					fjmap.put(fj[i], URLDecoder.decode(fileName, "utf-8"));
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			}
			model.addAttribute("fjmap", fjmap);
		}
		return "modules/approve/planApproveEdit";
	}
	
	/**
	 * 修改
	 * @param homeApprove
	 * @param model
	 * @param redirectAttributes
	 * @return
	 * @throws ParseException
	 */
	@RequiresPermissions("approve:planApprove:edit")
	@RequestMapping(value = "edit")
	public String edit(HomeApprove homeApprove, Model model, RedirectAttributes redirectAttributes) throws ParseException {
		if (!beanValidator(model, homeApprove)){
			return form(homeApprove, model);
		}
		try {
			if (homeApprove.getContentzy() != null) {
				homeApprove.setContentzy(StringEscapeUtils.unescapeHtml4(homeApprove.getContentzy()));
			}
			if (homeApprove.getZycontent() != null) {
				homeApprove.setZycontent(StringEscapeUtils.unescapeHtml4(homeApprove.getZycontent()));
			}
			if (homeApprove.getYyzl() != null) {
				homeApprove.setYyzl(StringEscapeUtils.unescapeHtml4(homeApprove.getYyzl()));
			}
			if (homeApprove.getFujian() != null) {
				homeApprove.setFujian(StringEscapeUtils.unescapeHtml4(homeApprove.getFujian()));
			}

			homeApproveService.save(homeApprove);
			addMessage(redirectAttributes, "修改成功！");
		}catch(Exception e) {
			addMessage(redirectAttributes, "修改失败！");
		}
		return "redirect:"+Global.getAdminPath()+"/approve/planApprove/?repage";
	}
	
	

}